package com.wy2cloud.sample.zuulandauthserver.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.wy2cloud.sample.zuulandauthserver.entity.AuthorizeAuthority;
import com.wy2cloud.sample.zuulandauthserver.entity.AuthorizeRole;
import com.wy2cloud.sample.zuulandauthserver.entity.AuthorizeUser;
import com.wy2cloud.sample.zuulandauthserver.entity.SecurityUser;
import com.wy2cloud.sample.zuulandauthserver.repository.AuthorizeAuthorityRepository;
import com.wy2cloud.sample.zuulandauthserver.repository.AuthorizeRoleRepository;
import com.wy2cloud.sample.zuulandauthserver.repository.AuthorizeUserRepository;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
    private AuthorizeUserRepository authorizeUserRepository;
	
	@Autowired
    private AuthorizeRoleRepository authorizeRoleRepository;
	
	@Autowired
    private AuthorizeAuthorityRepository authorizeAuthorityRepository;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //SUser对应数据库中的用户表，是最终存储用户和密码的表，可自定义
        //本例使用SUser中的email作为用户名:
		AuthorizeUser user = authorizeUserRepository.findUserByName(userName); //code8
		if (user == null) {
			throw new UsernameNotFoundException("UserName " + userName + " not found");
		}
		List<AuthorizeRole> roles = authorizeRoleRepository.listUserRoles(user.getId());
		List<AuthorizeAuthority> authorities = authorizeAuthorityRepository.listUserAuthorities(user.getId());
		// SecurityUser实现UserDetails并将SUser的Email映射为username
		return new SecurityUser(user,roles,authorities); //code9
	}
}
